<template>
  <div class="goodeDetils">
    <!-- 商品详情页面 -->
    <el-row :gutter="22">
      <el-col :span="9">
        <!-- 商品图片 -->
        <el-image :src="goods.picture">
          <template #error>
            <div class="image-slot">
              <el-icon><icon-picture /></el-icon>
            </div>
          </template>
        </el-image>
      </el-col>
      <el-col :span="13">
        <!-- 商品描述信息 -->
        <div style="height:200px;">
          <el-descriptions class="margin-top" title="商品详情" :column="2" border>
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">
                  计算机名称
                </div>
              </template>
              {{ goods.name }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">
                  分类
                </div>
              </template>
              {{ goods.assort }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">
                  售价
                </div>
              </template>
              <span style="color:red">￥</span> {{ goods.price }} <span style="color:red;">元</span>
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">
                  库存
                </div>
              </template>
              {{ goods.stock }} <span style="color:red">台</span>
            </el-descriptions-item>

            <el-descriptions-item>
              <template #label>
                <div class="cell-item">
                  数量
                </div>
              </template>
              <el-input-number v-model="goodsNum" :step="1" :min="1" /><span style="color:red;margin-left:10px;">台</span>
            </el-descriptions-item>
          </el-descriptions>

          <el-descriptions :column="1" border>
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">
                  操作
                </div>
              </template>
              <el-button @click="showAddress('cart')" type="danger" style="margin-left: 40px;">
                <el-icon>
                  <ShoppingCartFull />
                </el-icon>
                加入购物车
              </el-button>
              <el-button type="primary" @click="showAddress('indent')" style="margin-left: 40px;">
                <el-icon>
                  <Goods />
                </el-icon>
                直接下单
              </el-button>
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </el-col>
    </el-row>

    <el-divider />
    <div class="accessory">
      <!-- 配件列表信息 -->
      <div>配件列表</div>
      <!-- 表格展示 -->
      <el-table :data="accessoryList" border stripe style="width: 100%">
        <el-table-column prop="name" label="配件名称" width="150" />
        <el-table-column prop="assort.name" label="分类" />
        <el-table-column prop="systemArg" label="系统参数" />
        <el-table-column prop="sellPrice" label="销售价格" />
      </el-table>
    </div>

  </div>

  <!-- 展示地址列表 -->
  <el-dialog v-model="addressDialogVisible" title="请选择收货地址" width="60%">
    <el-button @click="addDialogVisible = true" type="primary">新增地址</el-button>
    <!-- 表格展示 -->
    <el-table :data="addressTable" highlight-current-row @current-change="selectAddress" stripe style="width: 100%">
      <el-table-column prop="name" label="名称" />
      <el-table-column prop="phone" label="收货电话" />
      <el-table-column prop="province" label="省" />
      <el-table-column prop="city" label="市" />
      <el-table-column prop="area" label="区" />
      <el-table-column prop="specific" label="具体地址" />
    </el-table>
  </el-dialog>

  <!-- 新增地址弹出框 -->
  <el-dialog v-model="addDialogVisible" title="新增地址信息" width="40%">
    <div class="addForm">
    <el-form label-position="right" :model="addform">
      <el-form-item label="收货人" class="addFormItem">
        <el-input v-model="addform.name" placeholder="请输入收货人" clearable />
      </el-form-item>
      <el-form-item label="收货电话" class="addFormItem">
        <el-input v-model="addform.phone" placeholder="收货电话" clearable/>
      </el-form-item>
      <el-form-item label="行政区划" class="addFormItem">
        <el-cascader
          v-model="division"
          :options="divisionTree"
          :props="props"
          filterable
        />
      </el-form-item>
      <el-form-item label="详细地址" class="addFormItem">
        <el-input v-model="addform.specific" placeholder="详细地址" />
      </el-form-item>
    </el-form>
  </div>
  <template #footer>
    <el-button type="primary" @click="addressAdd">新增</el-button>
    <el-button type="info" @click="addDialogVisible = false">取消</el-button>
  </template>
  </el-dialog>
</template>

<script setup>
import { onMounted, reactive, ref, watch } from 'vue';
import { useRoute } from 'vue-router';
import { getById } from '@/api/goods.js';
import { list, addAddress } from '@/api/address.js';
import { addCart } from '@/api/cart.js';
import { addIndent } from '@/api/indent.js'
import { getById as accessoryGetById } from '@/api/accessory.js';
import { Picture as IconPicture, ShoppingCartFull, Goods } from '@element-plus/icons-vue'
import { ElLoading, ElNotification } from 'element-plus';
import {getTreeData} from '@/utils/pca.js';


const route = useRoute()
const data = reactive({
  query: route.query
});
const goodsId = ref('');

// 行政区划所有数据
const divisionTree = ref([])
// 二级弹框展开的事件
const props = {
  expandTrigger: 'hover',
}
const addressTable = ref([]);
// 要操作的商品信息
const goods = reactive({
  id: null,
  assort: null,
  stock: null,
  name: null,
  picture: null,
  price: null,
  accessoryIdList: [],
});

const goodsNum = ref(0);
// 购买类型 car:加入购物车 indent：直接下单
const type = ref("car");

const addDialogVisible = ref(false);
// 配件集合
const accessoryList = ref([]);
// 地址弹框是否显示
const addressDialogVisible = ref(false);
// 订单弹框是否显示
const indentDialogVisible = ref(false);
// 新增表单
const addform = reactive({
  name: null,
  phone: null,
  province: null,
  city: null,
  area: null,
  specific: null,
})

// 行政区划选择的数据
const division = ref([]);

watch(()=>route.query,async(query)=>{
  if(query.goodsId){
    goodsId.value = query.goodsId;
  }
  await search()
})

onMounted(async () => {
  if(route.query) {
    goodsId.value = route.query.goodsId;
  }
  divisionTree.value = getTreeData();
  await search();
  await searchAccessoryList();
})


// 新增地址
const addressAdd = async()=>{
  console.log(division.value);
  addform.province = division.value[0];
  addform.city = division.value[1];
  addform.area = division.value[2];
  const loading = ElLoading.service({ fullscreen: true })
  await addAddress(addform);
  // 清空表单数据
  clearAddform();
  loading.close();
  division.value = [];
  addDialogVisible.value = false;
  await showAddress();
}

// 清空
const clearAddform = ()=>{
  addform.name = null;
  addform.phone = null;
  addform.province = null;
  addform.city = null;
  addform.area = null;
  addform.specific = null;
}

// 选中地址
const selectAddress = async (rowData) => {
  if (rowData == null) {
    // 提前返回
    return;
  }
  // 相关操作  
  const loading = ElLoading.service({ fullscreen: true });
  if (type.value == 'cart') {
    const cart = {};
    cart.addressId = rowData.id;
    cart.goodsId = goods.id;
    cart.goodsSum = goodsNum.value;
    await addCart(cart);
  } else if (type.value == 'indent') {
    const indent = {};
    indent.addressId = rowData.id;
    indent.goodsId = goods.id;
    indent.num = goodsNum.value;
    await addIndent(indent);

    // 弹框显示订单新增成功，请去订单中心支付
    ElNotification({
      title: "下单成功!",
      message: "订单新增成功，请去我的订单支付",
      type: 'success',
    })
    
  }
  // 新增成功后，关闭弹框
  addressDialogVisible.value = false;
  loading.close();
}

// 显示地址列表
const showAddress = async (value) => {
  // 存储起来后面为选择做判断
  type.value = value
  // 1. 查询本人所有地址列表
  const loading = ElLoading.service({ fullscreen: true })
  const response = await list()
  addressTable.value = response.data.data
  loading.close();
  addressDialogVisible.value = true;
}



// 查询商品信息
const search = async () => {
  const loading = ElLoading.service({ fullscreen: true });
  const response = await getById(goodsId.value);
  const repData = response.data.data;
  goods.id = repData.id;
  goods.name = repData.name;
  goods.picture = repData.picture;
  goods.accessoryIdList = repData.accessoryIdList;
  goods.stock = repData.stock;
  goods.price = repData.price;
  goods.assort = repData.assort;
  loading.close()
}


// 查询配件信息
const searchAccessoryList = async () => {
  for (let i = 0; i < goods.accessoryIdList.length; i++) {
    const response = await accessoryGetById(goods.accessoryIdList[i])
    accessoryList.value.push(response.data.data);
  }
}



</script>

<style scoped>
.accessory {
  margin-top: 40px;
}
</style>